
from javax.swing import JOptionPane, JFileChooser, filechooser
import _util
import _chart

def isnum(s):
  try:
    float(s)
    return True
  except:
    return False
	
def get_file_info():	
	defaultLocation = r"Q:\Q_Drive\StarOne\Filter_Test_Data\IMUX\TDHS_STAR_ONE_C4_ASS_1-23_FM"
	dirChooser = JFileChooser(defaultLocation)
	dirChooser.setMultiSelectionEnabled(True)
	dirChooser.setDialogTitle("Select all relevant folders")
	dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
	dirChooser.setAcceptAllFileFilterUsed(False)
	folderNames = dirChooser.showOpenDialog(dirChooser)
	all_dirnames = dirChooser.selectedFiles
	
	defaultPath = JFileChooser(all_dirnames[0])
	defaultPath.setMultiSelectionEnabled(False)
	defaultPath.setDialogTitle("Select default File Path")
	filePathNames = defaultPath.showOpenDialog(defaultPath)
	pathName = str(defaultPath.selectedFile)
	placeholder_filename = pathName.replace(str(all_dirnames[0])," ")
	parsed_ref_dirname = str(all_dirnames[0]).split('\\')
	new_filename = []
	for fName in all_dirnames:
		parsed_dirname = str(fName).split('\\')
		file_name = placeholder_filename.replace(str(parsed_ref_dirname[-1]),str(parsed_dirname[-1]))
		new_filename.append(str(fName) + file_name.strip())
	dummy1 = open_parse_data(new_filename)
		
def get_freq_plan():
	defaultLocation = 'Q:\Q_Drive\StarOne\Filter_Test_Data\S1C4_FreqTable.csv'
	fileChooser = JFileChooser(defaultLocation)
	ext_filter = filechooser.FileNameExtensionFilter("frequency plan in csv format(*.csv)",["csv"])
	fileChooser.setFileFilter(ext_filter)
	fileChooser.setMultiSelectionEnabled(False)
	fileChooser.setDialogTitle("Select Frequency plan to use")
	dummy1 = fileChooser.showOpenDialog(fileChooser)
	fName = str(fileChooser.selectedFile)
	f = open(fName)
	lines = [line for line in f]
	f.close()
	freq_data = [x.strip().split(',') for x in lines[6:]]
	freq_plan_data = []
	for y in range(len(freq_data)):
		temp_array = []
		temp_array.append(str(freq_data[y][1]))
		temp_array.append(float(freq_data[y][3]))
		freq_plan_data.append(temp_array) 
	return freq_plan_data
	

def open_parse_data(filename):
	_util.clear_console(console)
	#first_index = JOptionPane.showInputDialog("Please row number for the first data set")
	#last_index = JOptionPane.showInputDialog("Please row number for the last data set")
	first_index = 83
	last_index = 883
	freq_plan_data = get_freq_plan()
	for fname in filename:
		try:
		  f = open(fname)
		  lines = [line for line in f]
		  f.close()
		except Exception, e:
		  print(e)
		  return
		delimiter = fname.strip().split('\\')
		channel_name = fname[str(fname).index("."+delimiter[-2])-6:str(fname).index("."+delimiter[-2])]
		#Data extracted from file
		center_freq = []
		center_freq = [float(ch_freq) for ch_name,ch_freq in freq_plan_data if ch_name == channel_name]
		try:
			center_freq = center_freq[0]*1e6
		except:
			center_freq = 11 * 1e9
		strip_data = [x.strip().split(',') for x in lines[int(first_index)-1:int(last_index)-1]]
		freq_data, raw_data = zip(*strip_data)
		freq_data = [float(y)  for y in freq_data]
		freq_data_norm = [float(y) - center_freq for y in freq_data]
		raw_data = [float(z) for z in raw_data]
		parsed_filename = fname.strip().split('\\')
		fileLegend = parsed_filename[-1]
		#channel_name = fname[str(fname).index(".TV_")-6:str(fname).index(".TV_")]
		strip_data = zip(freq_data, raw_data)
		strip_data_norm = zip(freq_data_norm, raw_data)
		outerTabTitle = [['Absolute DL Frequency (MHz)', 'Uplink Frequency (MHz)', 'Normalized Gain (using MAX gain) (dB)'],
						  ['Normalized DL Frequency (MHz)', 'Downlink Frequency (MHz)', 'Normalized Gain (using MAX gain) (dB)']]
		plotTitle, x_axis, y_axis = zip(*outerTabTitle)
		
		if fname == filename[0]:
		  data_result = {}
		  data_result.update(_util.setTestResultDict('All', *plotTitle))
		  data_result['All'][plotTitle[0]].append((fileLegend, strip_data))
		  data_result['All'][plotTitle[1]].append((fileLegend, strip_data_norm))
		for key in data_result:
		  data_result[key][plotTitle[0]].append((fileLegend, strip_data))
		  data_result[key][plotTitle[1]].append((fileLegend, strip_data_norm))
	plot_frame1 = _chart.tabbed_plot_specs('IMUX Insertion Loss', data_result, outerTabTitle)
if __name__ == "__main__":
	_util.clear_console(console)
	get_file_info()